package com.jz.digital.utils;

import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Point;
import android.os.Build;
import android.provider.Settings;
import android.util.DisplayMetrics;
import android.util.Size;
import android.view.Display;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import androidx.appcompat.app.AppCompatActivity;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * 窗口工具类
 * Created by ZachLi on 2016/6/4.
 */
public class WindowUtil {

    /**
     * 获取屏幕大小
     * @param context
     * @return
     */
    public static Size getWindowSize(Context context){
        Resources resources = context.getResources();
        DisplayMetrics displayMetrics = resources.getDisplayMetrics();
        return new Size(displayMetrics.widthPixels,displayMetrics.heightPixels);
    }

    /**
     * 获取设备的真实屏幕大小,包含了底部NavigationBar的高度
     * @return 宽高size
     */
    public static Size getRealWindowSize(Context context) {
        if (context==null)return null;
        WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        if (windowManager == null) {
            return getWindowSize(context);
        }
        Display display = windowManager.getDefaultDisplay();
        Point screenResolution = new Point();
        display.getRealSize(screenResolution);
        return new Size(screenResolution.x, screenResolution.y);
    }

    /**
     * 判断当前是否为横屏
     *
     * @return 如果当前为横屏则返回 true;否则返回 false
     */
    public static boolean isHorizontalScreen(Context context) {
        Resources resources = context.getResources();
        Configuration configuration = resources.getConfiguration();
        int orientation = configuration.orientation;

        return orientation == Configuration.ORIENTATION_LANDSCAPE;
    }

    /**
     * 判断当前是否为竖屏
     *
     * @return 如果当前为竖屏则返回 true;否则返回 false
     */
    public static boolean isVerticalScreen(Context context){
        Resources resources = context.getResources();
        Configuration configuration = resources.getConfiguration();
        int orientation = configuration.orientation;

        return orientation == Configuration.ORIENTATION_PORTRAIT;
    }

    /**
     * 获取包括导航栏的屏幕宽高
     * @return
     */
    public static Size getFullScreenSize(Context context){
        if (context==null)return null;
        WindowManager windowManager =
                (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Display display = windowManager.getDefaultDisplay();
        Point screenResolution = new Point();
        display.getRealSize(screenResolution);
        return new Size(screenResolution.x,screenResolution.y);
    }

    /**
     * 设置全屏显示(隐藏状态栏与ActionBar)
     *
     * @param act
     */
    public static void setFullScreen(Activity act) {
        ActionBar actionBar = act.getActionBar();
        if (actionBar != null) {
            actionBar.hide();
        }
        View decorView = act.getWindow().getDecorView();
        decorView.setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LOW_PROFILE
                        | View.SYSTEM_UI_FLAG_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                        | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
    }

    public static void setTurlyFullScreen(Activity activity) {
        activity.getWindow().getDecorView()
                .setSystemUiVisibility(
                        View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY|
                        View.SYSTEM_UI_FLAG_FULLSCREEN|
                        View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
    }

    public static void setCameraActivityWindow(AppCompatActivity activity) {
        setTurlyFullScreen(activity);
        enableKeepScreen(activity, true);
        enableShowWhenLocked(activity, false);
        setBrightnessForCamera(activity, false);
    }

    /**
     * 隐藏导航栏
     * @param act
     */
    public static void hideNavigationBar(Activity act){
        View decorView = act.getWindow().getDecorView();
        int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION| View.SYSTEM_UI_FLAG_FULLSCREEN;
        decorView.setSystemUiVisibility(uiOptions);
    }

    /**
     * 设置屏幕方向为横屏,该操作会触发{@link Activity#onConfigurationChanged(Configuration)}
     * 与系统横屏方向相反
     * @param act
     */
    public static void setScreenOrientationToHorizontal(Activity act) {
        act.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
    }

    /**
     * 设置屏幕方向为竖屏,该操作会触发{@link Activity#onConfigurationChanged(Configuration)}
     * 与系统竖屏方向相反
     * @param act
     */
    public static void setScreenOrientationToPortrait(Activity act) {
        act.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT);
    }

    /**
     * 设置屏幕方向为横屏,该操作会触发{@link Activity#onConfigurationChanged(Configuration)}
     * 与系统横屏方向一致
     * @param act
     */
    public static void setScreenOrientationToHorizontalServer(Activity act) {
        act.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    }

    /**
     * 设置屏幕方向为竖屏,该操作会触发{@link Activity#onConfigurationChanged(Configuration)}
     * 与系统竖屏方向一致
     * @param act
     */
    public static void setScreenOrientationToPortraitServer(Activity act) {
        act.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }

    /**
     * 判断系统是否开启自动旋转
     *
     * @param context
     */
    public static boolean isAutoRotate(Context context) {
        //1表示已开启。0表示未开启
        int anInt = Settings.System.getInt(context.getContentResolver()
                , Settings.System.ACCELEROMETER_ROTATION, 0);
        return anInt == 1;
    }

    /**
     * 开启自动旋转
     *
     * @param context
     */
    public static void enableAutoRotate(Context context) {

        int anInt = Settings.System.getInt(context.getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 0);

        if (1 != anInt) {
            Settings.System.putInt(context.getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 1);
        }
    }

    /**
     * 开关屏幕常亮
     * @param activity
     * @param enable
     */
    public static void enableKeepScreen(Activity activity, boolean enable){
        if (enable) {
            activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        } else {
            activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        }
    }

    /**
     * 在锁屏界面之上
     * @param activity
     * @param enable
     */
    public static void enableShowWhenLocked(Activity activity, boolean enable){
        if (enable) {
            activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
        } else {
            activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
        }
    }

    /**
     * 设置屏幕亮度.
     * <p> 若 @code max 为 true 则会将屏幕调到最亮，false 则根据系统自适应</p>
     * @param activity
     * @param max
     */
    public static void setBrightnessForCamera(Activity activity, boolean max) {
        // 将屏幕调至最亮 - see http://stackoverflow.com/questions/11978042/android-screen-brightness-max-value
        WindowManager.LayoutParams layout = activity.getWindow().getAttributes();
        if (max) {
            layout.screenBrightness = WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_FULL;
        } else {
            layout.screenBrightness = WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_NONE;
        }
        activity.getWindow().setAttributes(layout);
    }

    /**
     * 设置屏幕亮度.
     * <p> 若 @code max 为 true 则会将屏幕调到最亮，false 则根据系统自适应</p>
     * @param activity
     * @param min
     */
    public static void setBrightnessForCameraMin(Activity activity, boolean min) {
        // 将屏幕调至最亮 - see http://stackoverflow.com/questions/11978042/android-screen-brightness-max-value
        WindowManager.LayoutParams layout = activity.getWindow().getAttributes();
        if (min) {
            layout.screenBrightness = WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_OFF;
        } else {
            layout.screenBrightness = WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_NONE;
        }
        activity.getWindow().setAttributes(layout);
    }

    // 根据亮度值修改当前window亮度
    public static void changeAppBrightness(Context context, int brightness) {
        Window window = ((Activity) context).getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        if (brightness == -1) {
            lp.screenBrightness = WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_NONE;
        } else {
            lp.screenBrightness = (brightness <= 0 ? 1 : brightness) / 255f;
        }
        window.setAttributes(lp);
    }

    public static int getSystemBrightness(Context context){
        // 获取系统亮度
        try {
            return Settings.System.getInt(context.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS);
        } catch (Settings.SettingNotFoundException e) {
            e.printStackTrace();
            return 255/2;
        }
    }

    /**
     * 显示状态栏
     * @param activity
     */
    public static void showStatusBar(Activity activity) {
        if (Build.VERSION.SDK_INT >= 19) {
            View decorView = activity.getWindow().getDecorView();
            //这里会保留状态栏的显示以保证软键盘弹出后界面不改变
            decorView.setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
        }
    }

    /**
     * 隐藏状态栏
     * @param activity
     */
    public static void hideStatusBar(Activity activity) {
        if (Build.VERSION.SDK_INT >= 19) {//
            View decorView = activity.getWindow().getDecorView();
            //设置真正的全屏
            decorView.setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                            | View.SYSTEM_UI_FLAG_FULLSCREEN);
        }
    }

    public static boolean isNotchScreen(Context context) {
        if (context==null)return false;
//        这个方法居然要手动设置了 LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES 才会返回true
//        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.P) {
//            DisplayCutout displayCutout = window.getDecorView().getRootWindowInsets().getDisplayCutout();
//            if (displayCutout != null) {
//                List<Rect> boundingRects = displayCutout.getBoundingRects();
//                return boundingRects != null && boundingRects.size() != 0;
//            }
//            return false;
//        }

        if (RomUtils.isXiaomi()) {
            try {
                ClassLoader cl = context.getClassLoader();
                Class SystemProperties = cl.loadClass("android.os.SystemProperties");
                Method get = SystemProperties.getMethod("getInt", String.class, int.class);
                return (Integer) get.invoke(SystemProperties, "ro.miui.notch", 0) == 1;
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (RomUtils.isHuawei()) {
            try {
                ClassLoader cl = context.getClassLoader();
                Class HwNotchSizeUtil = cl.loadClass("com.huawei.android.util.HwNotchSizeUtil");
                Method get = HwNotchSizeUtil.getMethod("hasNotchInScreen");
                return (boolean) get.invoke(HwNotchSizeUtil);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (RomUtils.isVivo()) {
            try {
                ClassLoader classLoader = context.getClassLoader();
                Class FtFeature = classLoader.loadClass("android.util.FtFeature");
                Method method = FtFeature.getMethod("isFeatureSupport", int.class);
                return  (boolean) method.invoke(FtFeature, 0x00000020);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (RomUtils.isOppo()) {
            return context.getPackageManager().hasSystemFeature("com.oppo.feature.screen.heteromorphism");
        } else if (RomUtils.isMeizu()) {
            try {
                Class clazz = Class.forName("flyme.config.FlymeFeature");
                Field field = clazz.getDeclaredField("IS_FRINGE_DEVICE");
                return (boolean) field.get(null);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return false;
    }
}
